<template>
  <div>
    <r-search
      :searchForm="searchForm"
      :searchHandle="searchHandle"
      :searchData="searchData"
    />
    <r-search :searchHandle="searchHandleAdd" />
    <r-table
      :isSelection="false"
      :isIndex="false"
      :isPagination="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="tablePage"
      @refresh="init()"
    ></r-table>
    <r-form
      :formRules="formRules"
      :formHandle="formHandle"
      :formData="formData"
      :formCols="formCols"
      ref="elForm"
      labelWidth="250px"
      dialogWidth="700px"
      :isHandle="true"
    />
    <r-form
      :formRules="formRulesEditPsw"
      :formHandle="formHandleEditPsw"
      :formData="formDataEditPsw"
      :formCols="formColsEditPsw"
      ref="elFormEditPsw"
      labelWidth="200px"
      dialogWidth="1000px"
      :isHandle="true"
    />
    <r-form
      :formRules="formRulesActive"
      :formHandle="formHandleActive"
      :formData="formDataActive"
      :formCols="formColsActive"
      ref="elFormActive"
      labelWidth="200px"
      dialogWidth="1000px"
      :isHandle="true"
    />

    <Affiliated_agents
      v-if="Affiliated_agents_data.show"
      v-on:Affiliated_agents_call="Affiliated_agents_call"
    >
    </Affiliated_agents>

    <Operation_record ref="Operation_record"></Operation_record>
    <!-- Maintenance Personnel绑定设备 -->
    <div>
      <el-dialog
        width="600"
        title="Maintenance Personnel Binding Device"
        :visible.sync="diveceShow"
      >
        <el-form style="display: flex;justify-content: center;">
          <el-form-item
            label="Maintenance Personnel"
            :label-width="formLabelWidth"
          >
            <el-select
              placeholder="Please Select Maintenance Personnel"
              :clearable="true"
              v-model="agentValue"
              style="width:320px"
            >
              <el-option
                v-for="item in agentArr"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <el-form style="display: flex;justify-content: center;">
          <el-form-item label="Device" :label-width="formLabelWidth">
            <el-select
              placeholder="Please Select Device"
              :clearable="true"
              v-model="agentIdValue"
              multiple
              style="width:320px"
            >
              <el-option
                v-for="item in agentIdArr"
                :key="item.id"
                :label="item.deviceNo"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-form style="display: flex;justify-content: center;">
          <el-form-item label="Device" :label-width="formLabelWidth">
            <el-checkbox
              v-model="agentIdChecked"
              :disabled="!agentValue || agentIdArr.length === 0 ? true : false"
              >Check All
            </el-checkbox>
          </el-form-item>
        </el-form>

        <div>
          Maintenance Personnel Already binding Device：
        </div>
        <el-table :data="inquireAgentData">
          <el-table-column
            property="deviceNo"
            align="center"
            label="Device Number"
          />
          <el-table-column
            property="deviceName"
            label="Device Name"
            align="center"
          />
        </el-table>

        <div slot="footer" class="dialog-footer">
          <el-button @click="diveceShow = false">Cancel</el-button>
          <el-button type="primary" @click="affirmAgentFn">Confirm</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import Affiliated_agents from "./cus/Affiliated_agents";
import Operation_record from "./cus/Operation_record";
export default {
  components: {
    Affiliated_agents,
    Operation_record
  },
  data() {
    var checkpass = (rule, value, callback) => {
      if (value != this.formData.password) {
        callback(new Error("The password is not the same!"));
      } else {
        callback();
      }
    };
    var checkpass2 = (rule, value, callback) => {
      if (value != this.formDataEditPsw.password) {
        callback(new Error("The password is not the same!"));
      } else {
        callback();
      }
    };
    return {
      Affiliated_agents_data: {
        show: false
      },
      searchData: {
        userName: "",
        phone: "",
        status: "",
        ctime: ""
      },
      searchForm: [
        {
          type: "input",
          prop: "userName",
          placeholder: "Maintenance Personnel Name",
          width: 340
        },
        {
          type: "input",
          prop: "phone",
          placeholder: "Phone",
          width: 180
        },
        {
          type: "date",
          prop: "ctime",
          placeholder: "Update Time",
          width: 240
        },
        {
          type: "select",
          prop: "status",
          placeholder: "Enable Status",
          width: 230,
          options: [
            {
              label: "Normal",
              value: "1"
            },
            {
              label: "Forbidden",
              value: "2"
            }
          ]
        }
      ],
      diveceShow: false,
      agentArr: [],
      agentIdArr: [],
      agentValue: "",
      agentIdValue: [],
      agentIdChecked: false,
      inquireAgentData: [],
      formLabelWidth: "160px",
      searchHandleAdd: [
        {
          label: "Add Maintenance Personnel",
          type: "primary",
          plain: true,
          icon: "el-icon-circle-plus-outline",
          handle: e => this.elFormVisible(),
          isShow: () =>
            sessionStorage.getItem("role") == "operator" ? true : false
        },
        {
          label: "Maintenance Personnel Binding Device",
          type: "primary",
          plain: true,
          handle: e => {
            this.diveceShow = true;
          }
        }
      ],
      searchHandle: [
        {
          label: "Search",
          type: "success",
          plain: true,
          icon: "el-icon-search",
          handle: e => {
            this.zeroFn();
            this.init();
          }
        },
        {
          label: "Reset",
          buttonss: true,
          icon: "el-icon-refresh-right",
          handle: e => {
            this.searchData = {
              userName: "",
              phone: "",
              status: "",
              ctime: ""
            };
            this.zeroFn();
            this.init();
          }
        }
      ],
      tableData: [],
      tableCols: [
        // {
        //     label: '序号',
        //     prop: 'id'
        // },
        {
          label: "Phone",
          prop: "phone"
        },
        {
          label: "Name",
          prop: "userName"
        },
        {
          label: "Authorization Message",
          prop: "openId"
        },
        {
          label: "Operator",
          prop: "operatorName"
        },
        {
          label: "Swap Cabinet Number",
          prop: "excNum",
          formatter: e => (e.excNum ? e.excNum : "--")
        },
        // {
        //     label: 'Charging Cabinet数量',
        //     prop: 'chrNum'
        // },
        {
          label: "Update Time",
          prop: "ctime"
        },
        {
          label: "Enable Status",
          prop: "status",
          values: [1, 2],
          type: "switch",
          change: async row => {
            const res = await this.apis.maintenancer_updata({
              id: row.id,
              status: row.status
            });

            this.$message({
              message: "Operations Success！",
              type: "success"
            });
          }
        },
        {
          label: "Operations",
          type: "button",
          width: 220,
          btnList: [
            // {
            //   label: '查看已关联Agent',
            //   type: 'text',
            //   handle: (row) => {
            //     this.Affiliated_agents_data.show=true;
            //   }
            // },
            {
              label: "Edit",
              type: "primary",
              plain: true,
              style: { "margin-bottom": "5px" },
              handle: row => this.elFormDetail(row)
            },
            {
              label: "Delete",
              type: "danger",
              plain: true,
              handle: row => {
                this.$confirm("Confirm Delete?", "Hint", {
                  confirmButtonText: "Confirm",
                  cancelButtonText: "Cancel",
                  type: "warning"
                })
                  .then(async () => {
                    var res = await this.apis.maintenancer_del({
                      id: row.id
                    });
                    this.$message({
                      type: "success",
                      message: "Delete Success!"
                    });
                    this.init();
                  })
                  .catch(() => {});
              }
            },
            {
              label: "Operations Record",
              type: "success",
              plain: true,
              handle: row => {
                this.$refs.Operation_record.showFun(row);
              }
            }
          ]
        }
      ],
      tablePage: { limit: 10, page: 1, total: 0 },
      formData: {
        userName: "",
        phone: ""
      },
      formCols: [
        {
          type: "input",
          label: "Maintenance Personnel Name",
          placeholder: "Please Input Maintenance Personnel Name",
          width: 350,
          prop: "userName"
        },
        {
          type: "input",
          label: "Phone",
          placeholder: "Please Input Maintenance Personnel Name",
          width: 350,
          prop: "phone"
        }
        // { type: "select", label: "选择User", placeholder: '', width: 350, prop: "phone", },
      ],
      formRules: {
        userName: [
          { required: true, message: "Please Input", trigger: "blur" }
        ],
        phone: [{ required: true, message: "Please Input", trigger: "blur" }]
        // account: [{ required: true, message: '账号', trigger: 'blur' },],
        // password: [{ required: true, message: '密码', trigger: 'blur' }],
        // enterPassword: [
        //     { required: true, validator: checkpass, message: '两次输入密码不一致', trigger: 'blur' },
        // ],
        // remark: [
        //     { required: true, message: 'Remarks', trigger: 'blur' },
        // ],
      },
      formHandle: [
        {
          label: "Cancel",
          handle: e => this.elFormVisible()
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmit()
        }
      ],
      //密码
      formDataEditPsw: {
        password: "",
        enterPassword: ""
      },
      formColsEditPsw: [
        {
          type: "input",
          inputType: "password",
          label: " Password",
          placeholder: "Please Input Password",
          width: 350,
          prop: "password"
        },
        {
          type: "input",
          inputType: "password",
          label: "Confirm Password",
          placeholder: "Please Input Confirm Password",
          width: 350,
          prop: "enterPassword"
        }
      ],
      formRulesEditPsw: {
        password: [{ required: true, message: "Password", trigger: "blur" }],
        enterPassword: [
          {
            required: true,
            message: "Please Input",
            trigger: "blur"
          },
          { validator: checkpass2 }
        ]
      },
      formHandleEditPsw: [
        {
          label: "Cancel",
          handle: e => this.elFormVisibleEditPsw()
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmitEditPsw()
        }
      ],
      //Forbidden恢复
      formDataActive: {
        // id: "",
      },
      formColsActive: [
        { label: "Recover/Forbidden Select Account", width: 350, prop: "" }
        // { type: "input", label: "确认密码", placeholder: 'Please Input确认密码', width: 350, prop: "enterPassword" },
      ],
      formRulesActive: {
        // name: [{ required: true, message: 'Maintenance PersonnelName', trigger: 'blur' },],
      },
      formHandleActive: [
        {
          label: "Cancel",
          handle: e => this.elFormVisibleActive()
        },
        {
          label: "Confirm",
          type: "primary",
          handle: e => this.elFormSubmitActive()
        }
      ]
    };
  },
  watch: {
    diveceShow: {
      handler(newValue, oldValue) {
        if (!newValue && oldValue) {
          this.agentValue = "";
          this.agentIdValue = [];
          this.agentIdArr = [];
        } else if (newValue && !oldValue) {
          this.agentValue = "";
          this.agentIdValue = [];
          this.agentIdArr = [];
        }
      },
      deep: true // 深度监听
    },
    agentValue: {
      handler(newValue) {
        if (newValue) {
          this.agentIdValue = [];
          this.agentIdChecked = false;
          this.inquireAgentFn(newValue);
          this.yesInquireAgentFn(newValue);
        } else {
          return;
        }
      },
      deep: true // 深度监听
    },
    agentIdChecked: {
      handler(newValue) {
        if (newValue) {
          this.agentIdValue = [];
          this.agentIdArr.forEach(i => {
            this.agentIdValue.push(i.id);
          });
          // console.log(2222, this.agentIdValue);
        } else {
          this.agentIdValue = [];
        }
      },
      deep: true // 深度监听
    }
  },
  computed: {},
  mounted() {
    this.init();
  },

  methods: {
    zeroFn() {
      this.tablePage.limit = 10;
      this.tablePage.page = 1;
      this.tablePage.total = 0;
    },
    // Maintenance Personnel绑定设备的确认按钮
    async affirmAgentFn() {
      // console.log(111111111111, this.agentValue, this.agentIdValue, this.agentIdArr);
      if (!this.agentValue) {
        this.$message({
          message: "Please Select Maintenance Personnel",
          type: "error"
        });
        return false;
      }
      if (this.agentIdValue.length === 0) {
        this.$message({
          message: "Please Select Device",
          type: "error"
        });
        return false;
      }
      this.diveceShow = false;
      let arr = [];
      this.inquireAgentData.forEach(i => {
        arr.push(i.deviceId);
      });
      this.agentIdValue = [...arr, ...this.agentIdValue];
      let params = {
        maintenancerId: this.agentValue,
        deviceIds: this.agentIdValue
      };
      let res = await this.apis.maintenancerDeviceBindOpt(params);
      this.$message({
        type: res.code == 200 ? "success" : "error",
        message: res.msg
      });
    },
    // 查询Maintenance Personnel  已  绑定的设备
    async yesInquireAgentFn(id) {
      this.inquireAgentData = [];
      let res = await this.apis.maintenancerListDeviceByOps(id);
      this.inquireAgentData = res.data || [];
    },
    // 查询Maintenance Personnel  未  绑定的设备
    async inquireAgentFn(id) {
      this.agentIdArr = [];
      let res = await this.apis.maintenancerListNotDeviceByOpt(id);
      this.agentIdArr = res.data || [];
    },
    Affiliated_agents_call() {
      this.Affiliated_agents_data.show = false;
    },
    async init() {
      this.tablePage.offset = this.tablePage.page;
      let param = {
        ...this.searchData,
        ...{
          pageNum: this.tablePage.page,
          pageSize: this.tablePage.limit,
          phone: this.searchData.phone,
          userName: this.searchData.userName,
          status: this.searchData.status
        }
      };
      // console.log(param);
      let res = await this.apis.maintenancer_list(param);
      if (res) {
        this.tablePage.total = res.total;
        this.tableData = res.rows || [];
        this.agentArr = [];
        this.tableData.forEach(i => {
          let testAgentArr = {
            id: i.id,
            name: i.userName
          };
          this.agentArr.push(testAgentArr);
        });
      }
    },
    async elFormSubmit() {
      this.$refs.elForm.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (!this.formData.id) {
            const res = await this.apis.maintenancer_save({
              phone: this.formData.phone,
              userName: this.formData.userName
            });
          } else {
            const res = await this.apis.maintenancer_updata({
              phone: this.formData.phone,
              userName: this.formData.userName,
              id: this.formData.id
            });
          }
          this.elFormVisible();
          this.init();
        }
      });
    },
    elFormDetail(row) {
      Object.keys(this.formData).forEach(key => {
        this.formData[key] = row[key];
      });
      this.formData.id = row.id;
      this.elFormVisible();
    },
    elFormDetailEditPsw(row) {
      Object.keys(this.formDataEditPsw).forEach(key => {
        this.formDataEditPsw[key] = row[key];
      });
      this.formDataEditPsw.id = row.id;
      this.formDataEditPsw.name = row.name;
      this.formDataEditPsw.phone = row.phone;
      this.formDataEditPsw.password = "";
      this.elFormVisibleEditPsw();
    },
    elFormVisibleEditPsw(tit) {
      if (this.$refs.elFormEditPsw.$refs.ruleFormEditPsw) {
        this.$refs.elFormEditPsw.$refs.ruleFormEditPsw.resetFields();
        this.$data.formDataEditPsw = this.$options.data.call(
          this
        ).formDataEditPsw;
      }
      this.$refs.elFormEditPsw.dialogFormVisible = !this.$refs.elFormEditPsw
        .dialogFormVisible;
      this.$refs.elFormEditPsw.dialogFormTitle = tit
        ? tit
        : this.formDataEditPsw.id
        ? "Edit"
        : "Add";

      if (this.$refs.elFormEditPsw.dialogFormVisible) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve();
          }, 2000);
        });
      }
    },
    async elFormSubmitEditPsw() {
      let res = await this.api.putop(this.formDataEditPsw);
      if (res) {
        this.formData.id = "";
        this.elFormVisibleEditPsw();
        this.init();
      }
    },
    //FrozenForbidden
    elFormDetailActive(row) {
      Object.keys(this.formDataActive).forEach(key => {
        this.formDataActive[key] = row[key];
      });
      this.formDataActive.id = row.id;
      this.elFormVisibleActive();
    },
    elFormVisibleActive(tit) {
      if (this.$refs.elFormActive.$refs.ruleFormActive) {
        this.$refs.elFormActive.$refs.ruleFormActive.resetFields();
        this.$data.formDataActive = this.$options.data.call(
          this
        ).formDataActive;
      }
      this.$refs.elFormActive.dialogFormVisible = !this.$refs.elFormActive
        .dialogFormVisible;
      this.$refs.elFormActive.dialogFormTitle = tit
        ? tit
        : this.formDataActive.id
        ? "Edit"
        : "Add";

      if (this.$refs.elFormActive.dialogFormVisible) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve();
          }, 2000);
        });
      }
    },
    async elFormSubmitActive() {
      let res = await this.api.opstate(this.formDataActive);
      if (res) {
        this.elFormVisibleActive();
        this.init();
      }
    }
  }
};
</script>
<style scoped lang="scss">
.el-icon-search {
  margin-right: 10px;
}

.Tip {
  margin-left: 20px;
}
</style>
